<template>
  <div class="medical-record-tab">
    <!-- 病历列表 -->
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <div class="record-list">
        <div 
          v-for="record in recordList" 
          :key="record.id" 
          class="record-item"
          @click="showRecordDetail(record)"
        >
          <div class="record-title">{{ record.title }}</div>
          <div class="record-info">
            <div class="record-time">记录时间: {{ formatDate(record.recordTime) }}</div>
            <div class="record-doctor">记录医生: {{ record.recordDoctorName || '未知' }}</div>
          </div>
          <van-icon name="arrow" class="arrow-icon" />
        </div>
        
        <!-- 空状态 -->
        <div v-if="recordList.length === 0 && !loading" class="empty-tip">
          <template v-if="hasError">
            <div class="error-text">加载失败</div>
            <van-button type="primary" size="small" @click="retryLoad">重试</van-button>
          </template>
          <template v-else>
            暂无病历数据
          </template>
        </div>
      </div>
    </van-list>
    
    <!-- 病历详情弹出层 -->
    <van-popup
      v-model:show="showDetail"
      position="bottom"
      overlay
      teleport="body"
      class="detail-popup"
      round
      closeable
    >
      <div class="detail-container">
        <div class="detail-header">病历详情</div>
        
        <div class="detail-content" v-if="currentRecord">
          <div class="record-detail-title">{{ currentRecord.title }}</div>
          
          <van-cell-group inset class="info-group">
            <van-cell title="记录类型" :value="getRecordTypeText(currentRecord.recordType)" />
            <van-cell title="记录时间" :value="formatDate(currentRecord.recordTime)" />
            <van-cell title="记录医生" :value="currentRecord.recordDoctorName || '未知'" />
          </van-cell-group>
          
          <van-cell-group inset title="病历内容" class="content-section">
            <div class="record-content">{{ currentRecord.content || '暂无内容' }}</div>
          </van-cell-group>
          
          <!-- 如果有病历图片 -->
          <van-cell-group inset title="病历图片" class="image-section" v-if="currentRecord.images && currentRecord.images.length">
            <div class="record-images">
              <van-image
                v-for="(url, index) in currentRecord.images"
                :key="index"
                :src="url"
                width="100"
                height="100"
                fit="cover"
                radius="4px"
                @click="showImagePreview(currentRecord.images, index)"
              />
            </div>
          </van-cell-group>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { showToast, showImagePreview } from 'vant';
import { getMedicalRecordList, getMedicalRecordDetail } from '@/api/patient';
import { requestWithRetry } from '@/utils/request';

const props = defineProps({
  visitId: {
    type: [String, Number],
    required: true
  }
});

// 病历列表数据
const recordList = ref([]);
const loading = ref(false);
const finished = ref(false);
const showDetail = ref(false);
const currentRecord = ref(null);
const hasError = ref(false);

// 获取病历列表
const fetchRecords = async () => {
  if (hasError.value) {
    finished.value = true;
    return;
  }
  
  try {
    loading.value = true;
    
    const data = {
      visitId: props.visitId
    };
    
    // 使用带重试机制的请求
    const res = await requestWithRetry({
      url: '/medicalRecord/list',
      method: 'post',
      data
    }, 2); // 最多重试2次
    
    if (res.data && res.data.length) {
      recordList.value = [...res.data];
    }
    
    // 加载完毕
    finished.value = true;
    hasError.value = false;
  } catch (error) {
    console.error('获取病历列表失败', error);
    showToast('获取病历列表失败');
    finished.value = true; // 确保出错时也设置完成状态，防止无限加载
    hasError.value = true;
  } finally {
    loading.value = false;
  }
};

// 上拉加载
const onLoad = () => {
  if (!loading.value && !finished.value) {
    fetchRecords();
  } else {
    // 如果正在加载或已完成，直接标记加载完成
    finished.value = true;
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  
  try {
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (e) {
    return dateStr;
  }
};

// 获取记录类型文本
const getRecordTypeText = (type) => {
  const typeMap = {
    1: '入院记录',
    2: '病程记录',
    3: '出院记录',
    4: '手术记录',
    5: '其他记录'
  };
  return typeMap[type] || '未知类型';
};

// 显示病历详情
const showRecordDetail = async (record) => {
  try {
    currentRecord.value = record;
    
    // 获取病历详情
    if (record.id) {
      // 使用带重试机制的请求
      const res = await requestWithRetry({
        url: '/medicalRecord/selectMedicalRecordById',
        method: 'get',
        params: { id: record.id }
      });
      
      if (res.data) {
        currentRecord.value = res.data;
        
        // 模拟病历图片数据
        if (!currentRecord.value.images) {
          currentRecord.value.images = [];
        }
      }
    }
    
    // 显示详情弹出层
    showDetail.value = true;
  } catch (error) {
    console.error('获取病历详情失败', error);
    showToast('获取病历详情失败');
  }
};

// 重试加载
const retryLoad = () => {
  if (hasError.value) {
    hasError.value = false;
    finished.value = false;
    recordList.value = [];
    fetchRecords();
  }
};

// 监听visitId变化，重新获取数据
watch(() => props.visitId, (newVal) => {
  if (newVal) {
    recordList.value = [];
    finished.value = false;
    hasError.value = false;
    fetchRecords();
  }
});

// 组件挂载后获取数据
onMounted(() => {
  fetchRecords();
});
</script>

<style scoped>
.medical-record-tab {
  padding: 0 0 20px 0;
}

.record-list {
  padding: 8px;
}

.record-item {
  background-color: #fff;
  margin-bottom: 8px;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
}

.record-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

.record-info {
  display: flex;
  flex-direction: column;
}

.record-time, .record-doctor {
  font-size: 14px;
  color: #666;
  margin-top: 2px;
}

.arrow-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 20px 0;
}

.error-text {
  color: #ee0a24;
  margin-bottom: 8px;
}

.detail-popup {
  height: 80%;
  max-height: 90vh;
}

.detail-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px 16px 24px;
}

.detail-header {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 16px;
  padding-top: 8px;
}

.detail-content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 16px;
}

.record-detail-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
  text-align: center;
  color: var(--primary-color, #1989fa);
}

.info-group {
  margin-bottom: 16px;
}

.content-section, .image-section {
  margin-top: 16px;
}

.record-content {
  padding: 16px;
  color: #333;
  line-height: 1.8;
  white-space: pre-wrap;
  font-size: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  min-height: 100px;
}

.record-images {
  padding: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: flex-start;
}
</style> 